package com.example.wac.service.login;

import com.example.wac.enums.ErrorCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wuancheng
 * @description
 * @date 2023-01-04 15:33:00
 */

@Component
public class LoginStrategy {

    private Map<String, AbstractLoginStrategy> loginStrategyMap;

    private static final List<String> TYPE = Arrays.asList("wx", "zfb");

    /**
     * ①构造方法注入 再通过this赋值给当前对象
     *
     * @param loginStrategyList
     */
    public LoginStrategy (List<AbstractLoginStrategy> loginStrategyList){
        this.loginStrategyMap = new HashMap<>(loginStrategyList.size());
        for (AbstractLoginStrategy loginStrategy : loginStrategyList) {
            loginStrategyMap.put(loginStrategy.getType(), loginStrategy);
        }
    }

//    /**
//     * ②set方法注入 再通过this赋值给当前对象
//     *
//     * @param loginStrategyList
//     */
//    @Autowired
//    public void setLoginStrategyMap (List<AbstractLoginStrategy> loginStrategyList){
//        this.loginStrategyMap = new HashMap<>(loginStrategyList.size());
//        for (AbstractLoginStrategy loginStrategy : loginStrategyList) {
//            loginStrategyMap.put(loginStrategy.getType(), loginStrategy);
//        }
//    }

    // ③注解（@Autowired，@Resource）直接注入

    /**
     * 根据登录方式获取对应的
     *
     * @param type 登录方式
     * @return
     */
    public String getByType(String type){
        if (StringUtils.isBlank(type)) {
            throw ErrorCode.PARAM_CANNOT_EMPTY.getAppException("登录方式");
        }
        if (!TYPE.contains(type)) {
            throw ErrorCode.OFTEN_EXCEPTION.getAppException("登录方式错误");
        }
        return loginStrategyMap.get(type).getToken();
    }
}
